'use strict'

const path = require('path');
const config = require('./config');
const Wechat = require('./wechat/wechat');
const wechatApi = new Wechat(config.wechat);

exports.reply = function *(next) {

    let message = this.weixin;

    if(message.MsgType === 'event') {

        // 事件推送
        if(message.Event === 'subscribe') {

            if(message.EventKey) {
                // console.log('扫描二维码加入' + message.EventKey + ' : ' + message.Ticket);
            }

            // console.log('test' + '消息id:' + message.MsgId);
            this.body = 'test' + '消息id:' + message.MsgId;
        } else if (message.Event === 'unsubscribe') {

            // console.log('无情取消关注');
            this.body = '';
        }
         else if(message.Event === 'LOCATION') {

            this.body = '你上报的位置' + message.latitude + '/' + message.Longitude + '-' + message.Precision;
        } else if(message.Event === 'CLICK') {

            this.body = '你点击了菜单' + message.EventKey;
        } else if(message.Event === 'SCAN') {

            // console.log('关注后扫二维码' + message.EventKey + ' ' + message.Ticket);
            this.body = '扫码';
        } else if(message.Event === 'VIEW') {

            this.body = '点击链接' + message.EventKey;
        }
    } else if(message.MsgType === 'text') {
        let content = message.Content;
        let reply = '';

        switch(content) {
            case 'news': {// 回复图文素材
                reply  = [{
                    title: '百度',
                    description: '点击访问百度',
                    picUrl: 'http://h.hiphotos.baidu.com/image/h%3D300/sign=7c7a8175855494ee982209191df7e0e1/c2cec3fdfc039245592ce1c58e94a4c27c1e255a.jpg',
                    url: 'https://www.baidu.com/'
                }, {
                    title: '掘金',
                    description: '点击访问掘金',
                    picUrl: 'http://b.hiphotos.baidu.com/image/h%3D300/sign=6f80124bc2134954611eee64664f92dd/ac6eddc451da81cb088429075b66d0160824319d.jpg',
                    url: 'https://juejin.im/timeline'
                }]
                break;
            };
            case 'image': {// 新增并回复临时图片素材
                let data = yield wechatApi.uploadMaterial('image', path.join(__dirname, '2.jpg'));
                reply = {
                    type: 'image',
                    mediaId: data.media_id
                }
                break;
            };
            case 'video': {// 新增并回复临时视频素材
                // 有问题，异步时间过久导致响应失败
                console.time('video');
                let data = yield wechatApi.uploadMaterial('video', path.join(__dirname, '5.mp4'));
                console.timeEnd('video');
                reply = {
                    type: 'video',
                    title: '视频回复',
                    description: 'eason',
                    mediaId: data.media_id
                }
                break;
            };
            case 'music': {// 新增并回复音乐素材
                console.time('music')
                let data = yield wechatApi.uploadMaterial('image', path.join(__dirname, '2.jpg'));
                console.timeEnd('music');
                reply = {
                    type: 'music',
                    title: '音乐回复',
                    description: '我们不一样',
                    musicUrl: 'http://sc1.111ttt.com/2017/1/11/11/304112002493.mp3',
                    thumMediaId: data.media_id,
                    HQMusicUrl: 'http://sc1.111ttt.com/2017/1/11/11/304112002493.mp3'
                }
                break;
            };
            case 'video-p': {// 新增并回复长久视频素材
                let data = yield wechatApi.uploadMaterial('video', path.join(__dirname, '5.mp4'), {
                    type: 'video', description: '{"title":"nice", "introduction":"easy"}'
                })

                reply = {
                    type: 'video',
                    title: '长久素材视频回复',
                    description: 'eason',
                    mediaId: data.media_id
                }
                break;
            };
            case 'image-p': {// 新增并回复长久图片素材
                let data = yield wechatApi.uploadMaterial('image', path.join(__dirname, '2.jpg'), { type: 'image' })

                reply = {
                    type: 'image',
                    mediaId: data.media_id
                }
                break;
            };
            case 'news-p': {// --新增并获取并回复永久图文素材
                let picData = yield wechatApi.uploadMaterial('image', path.join(__dirname, '2.jpg'), {});

                let media = {
                    articles: [{
                        title: 't百度',
                        thumb_media_id: picData.media_id,
                        author: 'ljx1',
                        digest: 'no digest1 haha',
                        show_cover_pic: 1,
                        content: 'no content1 hahha',
                        content_source_url: 'http://www.baidu.com'
                    }, {
                        title: '掘金',
                        thumb_media_id: picData.media_id,
                        author: 'ljx2',
                        digest: 'no digest2 haha',
                        show_cover_pic: 1,
                        content: 'no content2 hahha',
                        content_source_url: 'https://juejin.im/timeline'
                    }]
                };

                // start================================================
                let data = yield wechatApi.uploadMaterial('news', media, {});
                data = yield wechatApi.fetchMaterial(data.media_id, 'news', {});

                let items = data.news_item;
                let news = [];

                items.forEach(item => {
                    news.push({
                        title: item.title,
                        description: item.digest,
                        picUrl: picData.url,
                        url: item.url
                    })
                });
                reply = news;
                break;
            };
            case 'count': {// --获取素材总数、列表
                let counts = yield wechatApi.countMaterial();
                
                console.log(counts);

                let results = yield [
                    // type\offset\count
                    wechatApi.batchMaterial('image', 0, 10),
                    wechatApi.batchMaterial('news', 0, 10),
                    wechatApi.batchMaterial('video', 0, 10),
                    wechatApi.batchMaterial('voice', 0, 10)
                ];
                console.log(results);
                reply = 'success';
                break;
            };
            case 'tag-operate': {// 创建分组、获取所有标签
                // let tag = yield wechatApi.createTag('roommate11');

                // console.log('创建分组');
                // console.log(tag);

                // let tags = yield wechatApi.fetchTags();

                // console.log('获取分组');
                // console.log(tags);

                // let result = yield wechatApi.updateTag(tags.tags[tags.tags.length - 1].id, 'upupupmate');

                // tags = yield wechatApi.fetchTags();
                
                // console.log('修改好获取分组');
                // console.log(tags);

                // let result1 = yield wechatApi.delTag(tags[tags.length - 1].id)

                // console.log('删除分组');
                // console.log('result1')

                // reply = 'group success';
                break;
            };
            case 'fetch-user': {// 获取用户基本信息
                let data = yield wechatApi.fetchUsersInfo(message.FromUserName);

                console.log('单个用户信息获取');
                console.log(data);

                let u_list = [
                    {
                        openid: message.FromUserName,
                        lang: 'en'
                    }
                ]
                data = yield wechatApi.fetchUsersInfo(u_list);

                console.log('批量用户信息获取')
                console.log(data);

                reply = 'success';
                break;
            };
            case 'userlist': {// 获取用户列表
                let data = yield wechatApi.listUsers();
                console.log(data);
                reply = 'success';
                break;
            };
            case 'mass': {// 群发图文

                let mpnews = {
                    media_id: ''
                }

                let text = {
                    content: 'hello wechat!'
                }

                let msgData = yield wechatApi.sendByTag('mpnews', mpnews, 101)
            }
            default: reply = '收到你的消息：' + content;
        }

        // console.log(reply);
        this.body = reply;
    } else {
        // console.log('error');
        this.body = '';
    }

    yield next;
};
